package com.szxy.lockdemo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: zwz
 * @Date:2020/10/23 19:13
 * @Description:
 **/
public class MyCache {

    /**
     * map 线程共享可见
     */
    private volatile Map<String, String> map = new HashMap<>();

    /**
     * 共享锁
     */
    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();

    private ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();

    private ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();


    public void put(String key, String value) {
        try {
            writeLock.lock();
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName + "正在写...");
            Thread.sleep(1000);
            map.put(key, value);
            System.out.println(threadName + "put  key = " + key + " -value = " + value + "写入完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }

    public void get(String key) {
        try {
            readLock.lock();
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName + "正在读...");
            Thread.sleep(1000);
            String value = map.get(key);
            System.out.println(threadName + "get value = " + value + "读完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
    }


}
